import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 1、升序使用大根堆，把堆头元素和最后的元素进行交换，
 * 交换完成后向下调整时忽略已经有序的元素；
 * 从堆尾开始就是从大到小
 * User: 东莞呵呵
 * Date:2022-06-20
 * Time:11:08
 */
public class HeapSort {

    public static void heapSort(int[] array) {
        createHeap(array);
        int end = array.length - 1;//4、-1
        while (end > 0) {
            swap(array,end,0);
            ShiftDown(array,0, end);//1、end不是array.length
            end--;
        }
    }

    public static void createHeap(int[] array) {
        for (int parent = (array.length - 1 - 1) / 2; parent >= 0; parent--) {//3、parent>=0等于号不能没有
            ShiftDown(array, parent, array.length);
        }
    }

    // 向下调整，只能调整一棵子树
    public static void ShiftDown(int[] array, int parent, int len) {
        int child = parent * 2 + 1;
        while (child < len) {
            if (child + 1 < len && array[child] < array[child + 1]) {
                child++;
            }
            if (array[parent] < array[child]) {
                swap(array, parent, child);
                parent = child;
                child = parent * 2 + 1;
            }
            //2、break不能少
            else{
                break;
            }
        }
    }

    public static void swap(int[] array, int i, int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {65, 43, 5, 7, 4, 5, 76, 23, 4, 765, 42, 6, 7, 8};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
